package com.fare.taluo.application.impl.crawl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.application.crawl.TaskServiceApplication;
import com.fare.taluo.application.crawl.TaskTemplateApplication;
import com.fare.taluo.application.impl.crawl.crawlstatistics.CrawlStatisticsVOFilter;
import com.fare.taluo.util.DateUtils;
import com.fare.taluo.vo.core.StatisticsTotalDetailEntityVO;
import com.fare.taluo.vo.core.TaskInfoEntityVOVO;
import com.fare.taluo.vo.crawl.statistics.SingleLineCrawlStatisticsStatusVO;
import com.fare.taluo.vo.crawl.statistics.SingleLineCrawlStatisticsVO;
@Transactional
@Scope("singleton")
@Service("taskServiceApplication")

public class TaskServiceApplicationImpl implements TaskServiceApplication {
	//加载ＷＥＢＳＥＲＶＩＣＥＳ配置
//	@Resource(name ="iQueryTaskDetailApplicatioinService")
//	private IQueryTaskDetailApplicatioin iQueryTaskDetailApplicatioin; 
//					 
//	@Resource(name ="iStatisticsTaskInfoApplicationService")
//	private IStatisticsTaskInfoApplication iStatisticsTaskInfoApplication;
	
/*	@Override
	public List<StatisticsTotalDetailEntityVO> query(Long channelId, String from, String to, String flightDate) throws Exception {
		List<StatisticsTotalDetailEntityVO> listVo=new ArrayList<StatisticsTotalDetailEntityVO>();
		TaskModel[] models=iQueryTaskDetailApplicatioin.query(channelId, from,to,flightDate);
		listVo=explantionModel(models);
		
		return listVo;
	}*/
	
	/*//解释，转换Model
	public List<StatisticsTotalDetailEntityVO> explantionModel(TaskModel[] models){
		int modelSizes=models.length;
		List<StatisticsTotalDetailEntityVO> listVo=null;
		if(modelSizes>0){
			listVo=new ArrayList<StatisticsTotalDetailEntityVO>();
			for(int i=0;i<modelSizes;i++){
				TaskModel modelEntity=models[i];
				StatisticsTotalDetailEntityVO vo=new StatisticsTotalDetailEntityVO();
				vo.setStartTime(modelEntity.getStartTime());
				vo.setStartTimeStr(modelEntity.getStartTime()!=null ?DateUtils.dateToStr(modelEntity.getStartTime(), "yyyy-MM-dd HH:mm:ss"):null);
				vo.setEndTime(modelEntity.getEndTime());
				vo.setEndTimeStr(modelEntity.getEndTime() !=null?DateUtils.dateToStr(modelEntity.getEndTime(), "yyyy-MM-dd HH:mm:ss"):null);
				vo.setStatus(modelEntity.getStatus().longValue());
				vo.setFlightDate(modelEntity.getFlightDate());
				vo.setFromCity(modelEntity.getFromCity());
				vo.setFromCityName(modelEntity.getFromCityName());
				vo.setGrabChannelID(modelEntity.getGrabChannelId());
				vo.setGrabchannel(modelEntity.getGrabChannel());
				vo.setGrabdate(DateUtils.dateToStr(modelEntity.getCreateTime(), "yyyy-MM-dd"));
				vo.setSourceDataSize(modelEntity.getSourceDataSize().longValue());
				vo.setSourceDataSizeStr(modelEntity.getSourceDataSize()+"");
				vo.setToCity(modelEntity.getToCity());
				vo.setToCityName(modelEntity.getToCityName());
				vo.setCreateDate(DateUtils.dateToStr(modelEntity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				vo.setHbaseKey(modelEntity.getAttachHbaseKey());
				
				listVo.add(vo);
			}
		}
		
		
		return listVo;
	}
*/
	@Override
	public List<SingleLineCrawlStatisticsVO> listCrawlStatisticsVo(List<StatisticsTotalDetailEntityVO> list) {
		if(list.size()>0){
			Map<String,List<StatisticsTotalDetailEntityVO>> map=new HashMap<String,List<StatisticsTotalDetailEntityVO>>();
			map=this.pingjieSingleLineCrawl(list);
			
			List<SingleLineCrawlStatisticsVO> statusListListVo=new ArrayList<SingleLineCrawlStatisticsVO>();
			Object s[] = map.keySet().toArray();
			for(Map.Entry<String, List<StatisticsTotalDetailEntityVO>> reloverMap:map.entrySet()){
				SingleLineCrawlStatisticsVO statusListVo=new SingleLineCrawlStatisticsVO();
				List<SingleLineCrawlStatisticsStatusVO> statusVOlist=new ArrayList<SingleLineCrawlStatisticsStatusVO>();
				
//				List<StatisticsTotalDetailEntityVO> totalEntityVOList=reloverMap.getValue();
				String fromCity=reloverMap.getKey().split("\\--")[1];
				String fromCityName=reloverMap.getKey().split("\\--")[4];
				String toCityName=reloverMap.getKey().split("\\--")[5];
				String toCity=reloverMap.getKey().split("\\--")[3];
				String grabChannel=reloverMap.getKey().split("\\--")[0];
			//	String hbaseKey=reloverMap.getKey().split("\\--")[0];
				int grabChannelId=Integer.parseInt(reloverMap.getKey().split("\\--")[2]);
				statusListVo.setGrabChannel(grabChannel);
				statusListVo.setGrabChannelID(grabChannelId);
				List<TaskInfoEntityVOVO> taskInfoEntityVOList=new ArrayList<TaskInfoEntityVOVO>();
				taskInfoEntityVOList=InstanceFactory.getInstance(TaskTemplateApplication.class).findTaskInfoByConsdion(reloverMap.getKey().split("\\--")[2], fromCity, toCity);
				TaskInfoEntityVOVO taskInfoEntityVO=new TaskInfoEntityVOVO();
				if(taskInfoEntityVOList.size()>0){
					taskInfoEntityVO=taskInfoEntityVOList.get(0);
				}
				int frequency=24*60/(taskInfoEntityVO.getFrequency());//次数
				taskInfoEntityVO.getNextGrabTime();
				List<StatisticsTotalDetailEntityVO> totalEntityVOReList=CrawlStatisticsVOFilter.restructure(reloverMap.getValue(),taskInfoEntityVO.getFrequency());//重组后的List
				for(int i=0;i<frequency;i++){
					SingleLineCrawlStatisticsStatusVO statusVo=new SingleLineCrawlStatisticsStatusVO();
					StatisticsTotalDetailEntityVO totalEntityVO=new StatisticsTotalDetailEntityVO();
					if(totalEntityVOReList.size()>i){
						totalEntityVO=totalEntityVOReList.get(i);
						if(totalEntityVO.getEndTime() ==null && totalEntityVO.getStartTime() !=null){//正在抓取
							statusVo.setStatus(2);
							statusVo.setStartTime(totalEntityVO.getStartTime());
							statusVo.setStartTimeStr(totalEntityVO.getStartTimeStr());
						}else{//抓取完成
							statusVo.setStatus(1);
							statusVo.setFinishedStartTime(totalEntityVO.getEndTime());
							statusVo.setFinishedStartTimeStr(totalEntityVO.getEndTimeStr());
							statusVo.setStartTime(totalEntityVO.getStartTime());
							statusVo.setStartTimeStr(totalEntityVO.getStartTimeStr());
						}
						
					}else{//还 没有抓取
						statusVo.setStatus(3);
						
						statusVo.setNoBeginNextTime(taskInfoEntityVO.getNextGrabTime());
						statusVo.setNoBeginNextTimeStr(taskInfoEntityVO.getNextGrabTimeStr());
					}
					statusVo.setGrabChannel(grabChannel);
					statusVo.setGrabChannelID(grabChannelId);
				//	statusVo.setHbaseKey(hbaseKey);
					statusVo.setFromCity(fromCity);
					statusVo.setToCity(toCity);
					statusVo.setFromCityName(fromCityName);
					statusVo.setToCityName(toCityName);
					
					statusVOlist.add(statusVo);
				}
				statusListVo.setStatusDataVoList(statusVOlist);
				statusListListVo.add(statusListVo);
			}
			return statusListListVo;
			
		}
		
		return null;
	}
	
	
	public Map<String,List<StatisticsTotalDetailEntityVO>> pingjieSingleLineCrawl(List<StatisticsTotalDetailEntityVO> list){
		DecimalFormat r=new DecimalFormat(); 
		r.applyPattern("#0.00");//保留小数位数，不足会补零 
		Map<String,List<StatisticsTotalDetailEntityVO>> map=new LinkedHashMap<String,List<StatisticsTotalDetailEntityVO>>();
		List<StatisticsTotalDetailEntityVO> totaDetailList=null;
		List<StatisticsTotalDetailEntityVO> newVoList=null;
		for (int i = 0; i < list.size(); i++) {
			StatisticsTotalDetailEntityVO old=list.get(i);
			String key=old.getGrabchannel()+"--"+old.getFromCity()+"--"+old.getGrabChannelID()+"--"+old.getToCity()+"--"+old.getFromCityName()+"--"+old.getToCityName();//拼装成一个key
			if(map.get( key )!=null){//判断已经存在同个日期，同个渠道，成功数相同，实际抓取数相同，同一出发城市，同一到到达城市 的数据
				newVoList=map.get(key);//将存在的数据取出来
				newVoList.add(old);
				map.put(key,newVoList);
	       }else{
	    	   totaDetailList=new ArrayList<StatisticsTotalDetailEntityVO>();
	    	   totaDetailList.add(old);
	    	   map.put(key,totaDetailList);
	       }
		}
		
		return map;
	}

//	@Override
//	public List<StatisticsTotalDetailEntityVO> getDataForFinished(String fromCity, String toCity, String grabchannelID,String startTimeStr, String endTimeStr) {
//		Long grabchannelId=Long.parseLong(grabchannelID);
//		List<StatisticsTotalDetailEntityVO> list=new ArrayList<StatisticsTotalDetailEntityVO>();
//		try {
//			list=this.query(grabchannelId, fromCity, toCity, null);
//			if(list.size()>0){
//				return pingjie2(list, startTimeStr, endTimeStr);
//			}
//		} catch (Exception e) {
//			e.getMessage();
//		}
//		return null;
//	}
	
	private List pingjie2(List<StatisticsTotalDetailEntityVO> list,String startTimeStr,String endTimeStr){
		Map<String,StatisticsTotalDetailEntityVO> map=new LinkedHashMap<String,StatisticsTotalDetailEntityVO>();
		for (int i = 0; i < list.size(); i++) {
			StatisticsTotalDetailEntityVO old=list.get(i);
			//String key=old.getGrabdate()+"--"+old.getFromCity()+"--"+old.getFlightDate()+"--"+old.getToCity();//拼装成一个key
			Date startDateTime=old.getStartTime();
			Date endDateTime=old.getEndTime();
			Long startDateTime_to=0L;
			Long endDateTime_to =0L;
			Long toStartDateTime =0L;
			Long toEndDateTime=0L;
			if(endDateTime !=null && startDateTime!=null){
				startDateTime_to =DateUtils.strToDate(DateUtils.dateToStr(startDateTime, "yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss").getTime();
				endDateTime_to =DateUtils.strToDate(DateUtils.dateToStr(endDateTime, "yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss").getTime();
				//传过来的过滤时间
				toStartDateTime=DateUtils.strToDate(startTimeStr, "yyyy-MM-dd HH:mm:ss").getTime();
				toEndDateTime=DateUtils.strToDate(endTimeStr, "yyyy-MM-dd HH:mm:ss").getTime();
			}
			String key=old.getFromCity()+"--"+old.getFlightDate()+"--"+old.getToCity();//拼装成一个key
			if(flag(old.getFlightDate()) ){
				if(map.get( key )!=null && startDateTime_to>0 &&(startDateTime_to<=toStartDateTime && endDateTime_to<=toEndDateTime)){//判断已经存在同个日期，同个渠道，成功数相同，实际抓取数相同，同一出发城市，同一到到达城市 的数据
					StatisticsTotalDetailEntityVO newVo=map.get(key);//将存在的数据取出来
					  //累加
					Long total = nullToLong(old.getTotal(), newVo.getTotal());
					Long failNum = nullToLong(old.getFailNum(),newVo.getFailNum());
					Long actualNum = nullToLong(old.getActualNum(),newVo.getActualNum());
					Long successNum = nullToLong(old.getSuccessNum(),newVo.getSuccessNum());
					newVo.setTotal(total);
					newVo.setFailNum(failNum);
					newVo.setActualNum(actualNum );
					newVo.setSuccessNum(successNum);

					map.put(key, newVo);
		       }else{
		    	   if(old.getStatus()!=3){
		    		   old.setFailNum(1L);
		    		   old.setSuccessNum(0l);
		    	   }else{
		    		   old.setFailNum(0L);
		    		   old.setSuccessNum(1l);
		    	   }
		    	   old.setTotal(1l);
	    		   old.setActualNum(1l);
		    	   
		          map.put(key,old);
		       }
			}
		}
		Object s[] = map.keySet().toArray();
		for(int i = 0; i < map.size(); i++) {
			StatisticsTotalDetailEntityVO stu=map.get(s[i]);
		}
		List voList = new ArrayList();
		Iterator iter = map.entrySet().iterator();  //获得map的Iterator
		while(iter.hasNext()) {
			Entry entry = (Entry)iter.next();
			voList.add(entry.getValue());
		}
		return voList;
	}
	
	//与当前日期比较大小 2014-03-05
	public boolean flag(String dateStr){
		boolean flag=false;
		String nowaDaysStr=DateUtils.getDateStr("yyyy-MM-dd");
		Long nowaDays=DateUtils.strToDate(nowaDaysStr, "yyyy-MM-dd").getTime();
		Long dateDate=DateUtils.strToDate(dateStr, "yyyy-MM-dd").getTime();
		if(nowaDays<=dateDate){
			flag=true;
		}
		
		return flag;
	}
	//判断类型为空，赋值0
	private Long nullToLong(Long a,Long b){
		if(a!=null&&b!=null)
			return a+b;
		if(a==null & b==null)//这里用& 和  && 小心点
		    return 0l;
		if(a==null & b!=null)
			return b;
		if(b==null & a!=null)
			return a;
		return 0l;
	}
}
